<?php
namespace app\controller;

use think\facade\Db;
use think\Request;
use think\facade\View;
use think\helper\Str;
use think\exception\ValidateException;

include_once '../vendor/aliyun-green/aliyuncs/aliyun-php-sdk-core/Config.php';
use Green\Request\V20180509 as Green;

// 积分商品
class Yellow
{
    protected $accessKeyId = 'LTAIflf5ziysBMyJ';
    protected $accessKeySecret = 'yeqVHlqdZC4OqLl04KkgdUa02zvoxJ';

    /**
     * 函数用途描述
     * @date: 2019年6月6日
     * @author: Administrator
     * @return:
     */
    public function imageSync($imgurl='')
    {

        // $imgurl || $imgurl = $this->request->param('url/s','');

        if (!$imgurl) {
            return (['code'=>500,'msg'=>'请上传图片','data'=>[]]);
        }
        date_default_timezone_set("PRC");

        $ak = [
            'accessKeyId' => $this->accessKeyId,
            'accessKeySecret' => $this->accessKeySecret
        ];

        //请替换成你自己的accessKeyId、accessKeySecret
        $iClientProfile = \DefaultProfile::getProfile("cn-shanghai", $ak["accessKeyId"], $ak["accessKeySecret"]); // TODO
        \DefaultProfile::addEndpoint("cn-shanghai", "cn-shanghai", "Green", "green.cn-shanghai.aliyuncs.com");
        $client = new \DefaultAcsClient($iClientProfile);

        $request = new Green\ImageSyncScanRequest();
        $request->setMethod("POST");
        $request->setAcceptFormat("JSON");

        $task1 = array('dataId' =>  uniqid(),
            'url' => $imgurl,
            'time' => round(microtime(true)*1000)
        );
        $request->setContent(json_encode(array("tasks" => array($task1),
            "scenes" => array("porn","terrorism"))));

        try {
            $response = $client->getAcsResponse($request);
            if (200 == $response['code']) {
                $taskResults = $response['data'];
                foreach ($taskResults as $taskResult) {
                    if(200 == $taskResult['code']){
                        $sceneResults = $taskResult['results'];
                        foreach ($sceneResults as $sceneResult) {
                            $scene = $sceneResult['scene'];
                            $suggestion = $sceneResult['suggestion'];
                            //根据scene和suggetion做相关的处理
                            //do something
                            if($suggestion != 'pass'){
                                $arr = [
                                    'porn' => '识别图片中有色情内容',
                                    'terrorism' => '识别图片中有暴恐涉政内容。'
                                ];
                                return ['code'=>500,'data'=>[],'msg'=>$arr[$scene]];
                            }
                        }

                        //正常
                        return (['code'=>200,'data'=>[],'msg'=>'']);
                    } else {
                        //print_r("task process fail:" + $response->code);
                        return (['code'=>500,'data'=>[],'msg'=>$response['code'].':'.$response['msg']]);
                    }
                }
            } else {
                //print_r("detect not success. code:" + $response->code);
                return ['code'=>500,'data'=>[],'msg'=>$response['code'].':'.$response['msg']];
            }
        } catch (\Exception $e) {
            $code = $e->getCode();
            $error_message = $e->getMessage();
            return ['code'=>500,'data'=>[],'msg'=>$code.": ".$error_message];
        }
    }


    /**
     * 函数用途描述
     * @date: 2019年6月6日
     * @author: Administrator
     * @return:
     */
    public function videoSync($videoUrl='')
    {
        // $videoUrl || $videoUrl = $this->request->param('url/s','');

        if (!$videoUrl) {
            return ['code'=>500,'data'=>[],'msg'=>'请上传视频'];
        }
        $videoInfo = $this->getVideoInfo($videoUrl);
        $count = 10;

        if($videoInfo[0]['play_time'] < 10){
            $count = (int)$videoInfo[0]['play_time'];
        }
        $imgs = [];
        for ($i = 0; $i < $count; $i++) {
            $cover = './uploads/tmp/'.rand(11111, 99999).'_'.$i.'.jpg';//20190603171236733722
            //-ss 放在前面 快了 2-3倍
            exec('/usr/local/ffmpeg/bin/ffmpeg  -ss '.$i.' -i '.$videoUrl.' -y -f image2 -t 0.001 -s 750x422 '.$cover);
            $imgs[] = [
                'offset' => $i,
                'url' => $file = \think\facade\Request::domain() . substr($cover,1)
            ];
        }
        //pre($imgs);
        $iClientProfile = \DefaultProfile::getProfile("cn-shanghai", $this->accessKeyId, $this->accessKeySecret);
        \DefaultProfile::addEndpoint("cn-shanghai", "cn-shanghai", "Green", "green.cn-shanghai.aliyuncs.com");
        $client = new \DefaultAcsClient($iClientProfile);
        $request = new Green\VideoSyncScanRequest();
        $request->setMethod("POST");
        $request->setAcceptFormat("JSON");

        // 计费按照该处传递的场景进行
        // 一次请求中可以同时检测多个视频，每个视频可以同时检测多个风险场景，计费按照场景和视频截帧数计算
        // 例如：检测2个视频，场景传递porn,terrorism，计费会按照2个视频的截帧总数乘以鉴黄场景的价格加上2个视频的截帧总数乘以暴恐检测场景的费用计算//本地文件先进行上传，然后进行检测
        $task1 = array(
            'frames' => $imgs
        );

        $request->setContent(json_encode(array("tasks" => array($task1),
            "scenes" => array("porn", "terrorism"))));
        try {
            $response = $client->getAcsResponse($request);
            //删除图片
            $dir  = scandir('./uploads/tmp/');
            foreach ($dir as $key => $value){
                if(is_file('./uploads/tmp/'.$value)) {
                    unlink('./uploads/tmp/'.$value);
                }
            }
            if (200 == $response['code']) {
                $taskResults = $response['data'];
                foreach ($taskResults as $taskResult) {
                    if(200 == $taskResult['code']){
                        $sceneResults = $taskResult['results'];
                        foreach ($sceneResults as $sceneResult) {
                            $scene = $sceneResult['scene'];
                            $suggestion = $sceneResult['suggestion'];
                            //根据scene和suggetion做相关处理
                            //do something
                            if ($suggestion != 'pass') {
                                $arr = [
                                    'porn' => '识别视频中有色情内容',
                                    'terrorism' => '识别视频中有暴恐涉政内容。'
                                ];
                                return ['code'=>500,'data'=>[],'msg'=>$arr[$scene]];
                            }
                        }
                    } else {
                        //print_r("task process fail:" + $response->code);
                        return ['code'=>500,'data'=>[],'msg'=>"task process fail:" . $response['code']];
                    }
                }
                //正常
                return (['code'=>200,'data'=>[],'msg'=>'']);
            } else {
                return ['code'=>500,'data'=>[],'msg'=>"response process fail:" . $response['code']];
            }
        } catch (\Exception $e) {
            //print_r($e);
            $code = $e->getCode();
            $error_message = $e->getMessage();
            return ['code'=>500,'data'=>[],'msg'=>$error_message];
        }

    }

    /**
     * 文字鉴黄（垃圾文本检测）
     * @date: 2019年6月10日
     * @author: Administrator
     * @return:
     */
    public function textSync($text='')
    {

        if (!$text) {
            return ['code'=>500,'data'=>[],'msg'=>'请输入内容'];
        }
        $ak = [
            'accessKeyId' => $this->accessKeyId,
            'accessKeySecret' => $this->accessKeySecret
        ];
        //请替换成你自己的accessKeyId、accessKeySecret
        $iClientProfile = \DefaultProfile::getProfile("cn-shanghai", $ak["accessKeyId"], $ak["accessKeySecret"]); // TODO
        \DefaultProfile::addEndpoint("cn-shanghai", "cn-shanghai", "Green", "green.cn-shanghai.aliyuncs.com");
        $client = new \DefaultAcsClient($iClientProfile);

        $request = new Green\TextScanRequest();
        $request->setMethod("POST");
        $request->setAcceptFormat("JSON");

        $task1 = array('dataId' =>  uniqid(),
            'content' => $text
        );
        $request->setContent(json_encode(array("tasks" => array($task1),
            "scenes" => array("antispam"))));

        try {
            $response = $client->getAcsResponse($request);
            if(200 == $response['code']){
                $taskResults = $response['data'];
                foreach ($taskResults as $taskResult) {
                    if (200 == $taskResult['code']) {
                        $sceneResults = $taskResult['results'];
                        foreach ($sceneResults as $sceneResult) {
                            $scene = $sceneResult['label'];
                            $suggestion = $sceneResult['suggestion'];
                            //根据scene和suggetion做相关的处理
                            //do something
                            if ($suggestion != 'pass') {
                                $arr = [
                                    'normal'=> '正常文本',
                                    'spam'=> '含垃圾信息',
                                    'ad'=> '广告',
                                    'politics'=> '涉政',
                                    'terrorism'=> '暴恐',
                                    'abuse'=> '辱骂',
                                    'porn'=> '色情',
                                    'flood'=> '灌水',
                                    'contraband'=> '违禁',
                                    'meaningless'=> '无意义',
                                    'customized'=> '自定义关键词',
                                ];
                                return ['code'=>500,'data'=>[],'msg'=>'内容含有【'.$arr[$scene].'】内容, 请修改后重新提交'];
                            }
                        }
                    } else {
                        return ['code'=>500,'data'=>[],'msg'=>"请求失败1:" + $response['code']];
                    }
                }

                //正常
                return (['code'=>200,'data'=>[],'msg'=>'']);
            } else {
                return ['code'=>500,'data'=>[],'msg'=>"请求失败2:" . $response['code']];
            }

        } catch (\Exception $e) {
            $code = $e->getCode();
            $error_message = $e->getMessage();
            return ['code'=>500,'data'=>[],'msg'=>$code.": ".$error_message];
        }

    }


    /* 使用ffmpeg获取视频信息
     * @param  String $file 视频文件
     * @return Array
     */
    public function getVideoInfo($file)
    {

        ob_start();
        passthru(sprintf('/usr/local/ffmpeg/bin/ffmpeg -i "%s" 2>&1', $file));
        $video_info = ob_get_contents();


        ob_end_clean();    // 使用输出缓冲，获取ffmpeg所有输出内容

        $ret = array();    // Duration: 00:33:42.64, start: 0.000000, bitrate: 152 kb/s

        if (preg_match("/Duration: (.*?), start: (.*?), bitrate: (\d*) kb\/s/", $video_info, $matches)){
            $ret['duration'] = $matches[1]; // 视频长度

            $duration = explode(':', $matches[1]);
            $ret['seconds'] = $duration[0]*3600 + $duration[1]*60 + $duration[2]; // 转为秒数

            $ret['start'] = $matches[2]; // 开始时间

            $ret['bitrate'] = $matches[3]; // bitrate 码率 单位kb

        }
        // Stream #0:1: Video: rv20 (RV20 / 0x30325652), yuv420p, 352x288, 117 kb/s, 15 fps, 15 tbr, 1k tbn, 1k tbc

        if (preg_match("/Video: (.*?), (.*?), (.*?), (.*?)[,\s]/", $video_info, $matches)) {
            $ret['vcodec'] = $matches[1];     // 编码格式

            $ret['vformat'] = $matches[2];    // 视频格式

            //$ret['resolution'] = $matches[4]; // 分辨率

            if (strpos($matches[3],'x') !== false) {
                if (strpos($matches[3],'[') !== false) {
                    $arr = explode(' ',$matches[3]);
                    $ret['resolution'] = $arr[0];
                } else {
                    $ret['resolution'] = $matches[3];
                }
            } else {
                if (strpos($matches[4],'x') !== false) {
                    if (strpos($matches[4],'[') !== false) {
                        $arr = explode(' ',$matches[4]);
                        $ret['resolution'] = $arr[0];
                    } else {
                        $ret['resolution'] = $matches[4];
                    }
                }
            }

            // list($width, $height) = explode('x', $matches[3]);
            // $ret['width'] = $width;
            // $ret['height'] = $height;

        }    // Stream #0:0: Audio: cook (cook / 0x6B6F6F63), 22050 Hz, stereo, fltp, 32 kb/s

        if (preg_match("/Audio: (.*), (\d*) Hz/", $video_info, $matches)) {
            $ret['acodec'] = $matches[1];      // 音频编码

            $ret['asamplerate'] = $matches[2]; // 音频采样频率

        }
        if (isset($ret['seconds']) && isset($ret['start'])) {
            $ret['play_time'] = $ret['seconds'] + $ret['start']; // 实际播放时间

        }
        $ret['size'] = filesize($file); // 视频文件大小

        //$video_info = iconv('gbk','utf8', $video_info);
        $video_info = iconv('UTF-8','GB2312//TRANSLIT//IGNORE',$video_info);
        return array($ret, $video_info);

    }
}